package org.example.service;

import com.alipay.api.AlipayClient;
import com.alipay.api.FileItem;
import com.alipay.api.request.AlipayOfflineMaterialImageUploadRequest;
import com.alipay.api.response.AlipayOfflineMaterialImageUploadResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.config.AlipayConfig;
import org.example.model.dto.ImageUploadRequest;

import java.io.File;

/**
 * 图片上传服务
 * 用于上传商家进件所需的各类资质图片
 */
@Slf4j
public class ImageUploadService {

    private final AlipayClient alipayClient;

    /**
     * 构造方法
     * @param config 支付宝配置
     */
    public ImageUploadService(AlipayConfig config) {
        this.alipayClient = config.createAlipayClient();
    }

    /**
     * 上传图片到支付宝
     *
     * @param request 图片上传请求
     * @return 支付宝返回的图片URL
     */
    public String uploadImage(ImageUploadRequest request) {
        try {
            log.info("开始上传图片，类型：{}, 路径：{}", request.getImageType(), request.getImageFilePath());

            // 检查文件是否存在
            File imageFile = new File(request.getImageFilePath());
            if (!imageFile.exists()) {
                log.error("图片文件不存在：{}", request.getImageFilePath());
                throw new RuntimeException("图片文件不存在");
            }

            // 构建请求
            AlipayOfflineMaterialImageUploadRequest alipayRequest = new AlipayOfflineMaterialImageUploadRequest();
            alipayRequest.setImageType(request.getImageType());

            // 设置图片内容
            FileItem imageContent = new FileItem(imageFile);
            alipayRequest.setImageContent(imageContent);

            // 设置图片名称（如果有）
            if (request.getImageName() != null) {
                alipayRequest.setImageName(request.getImageName());
            } else {
                alipayRequest.setImageName(imageFile.getName());
            }

            // 调用API
            AlipayOfflineMaterialImageUploadResponse response = alipayClient.execute(alipayRequest);

            if (response.isSuccess()) {
                String imageUrl = response.getImageUrl();
                log.info("图片上传成功，URL：{}", imageUrl);
                return imageUrl;
            } else {
                log.error("图片上传失败 - code: {}, msg: {}, subCode: {}, subMsg: {}",
                        response.getCode(), response.getMsg(),
                        response.getSubCode(), response.getSubMsg());
                throw new RuntimeException("图片上传失败：" + response.getSubMsg());
            }

        } catch (Exception e) {
            log.error("上传图片异常", e);
            throw new RuntimeException("上传图片异常：" + e.getMessage(), e);
        }
    }

    /**
     * 批量上传图片
     *
     * @param requests 图片上传请求列表
     * @return 图片URL数组
     */
    public String[] uploadImages(ImageUploadRequest[] requests) {
        String[] imageUrls = new String[requests.length];
        for (int i = 0; i < requests.length; i++) {
            imageUrls[i] = uploadImage(requests[i]);
        }
        return imageUrls;
    }
}
